import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '@/views/index/index.vue'
import RegisterUser from '@/views/register/register.vue'
import UserLogin from '@/views/login/login.vue'
import store from '@/store'
// 首页内容
import indexConnect from '@/views/index/indexConnect'
// 文章管理
// 文章分类
import Assort from '@/views/article/articleAssort'
// 文章列表
import Tabulation from '@/views/article/articleTabulation'
// 发表文章
import Publish from '@/views/article/articlePublish'

// 个人中心
// 基本资料
import basicInfo from '@/views/myselfdata/basicInfo'
// 更换头像
import replaceHead from '@/views/myselfdata/replaceHead'
// 重置密码
import resetPassword from '@/views/myselfdata/resetPassword'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/indexConnect' },
  { path: '/index', redirect: '/indexConnect' },

  {
    path: '/index',
    name: 'Index',
    component: Index,
    children: [
      // 首页内容
      { name: 'indexConnect', path: '/indexConnect', component: indexConnect },
      // 文章分类子路由
      // 文章分类
      { name: 'assort', path: '/assort', component: Assort },
      // 文章列表
      { name: 'tabulation', path: '/tabulation', component: Tabulation },
      { name: 'publish', path: '/publish', component: Publish },

      // 个人中心子路由
      // 基本资料
      { name: 'basicInfo', path: '/basicInfo', component: basicInfo },
      // 更换头像
      { name: 'replaceHead', path: '/replaceHead', component: replaceHead },
      // 重置密码
      { name: 'resetPassword', path: '/resetPassword', component: resetPassword }

    ]
  },
  { path: '/reg', name: 'RegisterUser', component: RegisterUser },
  { path: '/login', name: 'UserLogin', component: UserLogin }

]

const router = new VueRouter({
  routes
})

// 定义路由白名单
const whiteList = ['/login', '/reg']
// 进入路由拦截
router.beforeEach((to, from, next) => {
  // to  去哪里,
  // from 从哪来,
  // next()是否放行
  // 如果next() 调用就是放行
  // next(路径)拦截到某个路径页面

  // 获取仓库的token
  const token = store.state.user.token

  // 判断是否有token
  if (token) {
    next()
    return
  }

  // 判断访问的路由是否在白名单内
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 访问的不是白名单路由并且没有 token 直接拦截跳转至 /login 路由
  next('/login')
})

// // 离开路由拦截
// router.beforeResolve((to, from, next) => {
//   console.log(to)
//   console.log(from)
//   next()
// })
// 获取原型对象push函数
const VueRouterPush = VueRouter.prototype.push
// 修改原型对象中的push函数
VueRouter.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

export default router
